package cn.tworice.blog.web;

import cn.tworice.blog.entity.CountIp;
import cn.tworice.blog.service.ToolsService;
import cn.tworice.blog.utils.CoreService;
import com.lmk.core.web.support.api.RequestResult;
import com.lmk.core.web.support.api.StatusCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;


@RestController
@RequestMapping("/api/index")
@CrossOrigin
@Api(tags = "杂项接口")
public class IndexController {

    @Autowired
    private ToolsService toolsService;


    @ApiOperation("登录接口")
    @PostMapping("login")
    public RequestResult login(@ApiParam("用户名") @RequestParam(value = "name",required = false,defaultValue = "username") String name,@RequestParam(value = "pwd",required = false,defaultValue = "password") @ApiParam("密码") String pwd){
        System.out.println(name+pwd);
        RequestResult result = new RequestResult();
        if(name.equals("wyn") && pwd.equals("fn")){
            result.setCode(new StatusCode(200,"登录成功"));
        }else {
            result.setCode(new StatusCode(401,"登录失败"));
        }
        return result;
    }


    @GetMapping("div/{a}.html")
    @ApiOperation("rest风格接口")
    public RequestResult rest(@ApiParam("被除数") @PathVariable("a") String a){
        RequestResult result = new RequestResult();
        int i=1/0;
        result.setCode(new StatusCode(200,"请求成功"));
        result.appendData("sum",a);
        return result;
    }


    @GetMapping("getIp")
    @ApiOperation("获取IP地址")
    public RequestResult getIp(HttpServletRequest request){
        RequestResult result = new RequestResult();
        String ipAddress = CoreService.getIpAddress(request);

        // 保存访问记录
        new Thread(()->{
            CountIp countIp = new CountIp();
            countIp.setTime(new Date().getTime());
            countIp.setIp(ipAddress);
            countIp.setUrl(request.getRequestURI()); // 接口
            toolsService.saveCallIP(countIp);
        },"t1").start();

        result.setCode(new StatusCode(200, "获取IP地址！"));
        result.appendData("ip", ipAddress);
        return result;
    }


    @ApiOperation("晋源区一键签到")
    @GetMapping("QsignIn")
    public RequestResult signIn(){
        RequestResult result = new RequestResult();
        try{
            String s=toolsService.signIn();

            result.setCode(new StatusCode(200,"签到成功"));
            result.appendData("result",s);
        }catch (Exception ex){
            ex.printStackTrace();
            result.setCode(new StatusCode(500,"签到失败"));
        }
        return result;
    }
}
